﻿#region using statements
using System;
using System.IO;
using System.Windows.Documents;
using System.Windows.Xps.Packaging;
using System.Windows.Media.Imaging;
#endregion


namespace XPS2Image.Library
{
    public static class FileConversions
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xpsFileName"></param>
        /// <param name="pages"></param>
        static public void SaveXpsPageToJpeg(string xpsFileName, int[] pages)
        {
            using (XpsDocument xpsDoc = new XpsDocument(xpsFileName, System.IO.FileAccess.Read))
            {
                FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence();
                DocumentPaginator paginator = docSeq.DocumentPaginator;

                // You can get the total page count from docSeq.PageCount

                foreach (int pageNum in pages)
                {
                    using (DocumentPage docPage = paginator.GetPage(pageNum))
                    {
                        BitmapImage bitmap = new BitmapImage();
                        RenderTargetBitmap renderTarget =
                            new RenderTargetBitmap((int)docPage.Size.Width,
                                                    (int)docPage.Size.Height,
                                                    96, // WPF (Avalon) units are 96dpi based
                                                    96,
                                                    System.Windows.Media.PixelFormats.Default);

                        renderTarget.Render(docPage.Visual);

                        JpegBitmapEncoder encoder = new JpegBitmapEncoder();  // Choose type here ie: JpegBitmapEncoder, etc
                        encoder.Frames.Add(BitmapFrame.Create(renderTarget));

                        using (FileStream pageOutStream = new FileStream(xpsDoc + ".Page" + pageNum + ".jpg", FileMode.Create, FileAccess.Write))
                        {
                            encoder.Save(pageOutStream);
                            pageOutStream.Close();
                        }
                    }
                }
            }
        }
    }
}
